package com.mall.action;

import com.mall.uitl.JsonUtil;
import com.mall.uitl.OSSProperties;
import com.mall.uitl.UploadFileUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Properties;

/**
 * @author lwd1513
 * @date 2022-03-27 20 43
 * discription
 */

@RestController
@RequestMapping("OSSFileUploadServlet")
public class OSSFileUploadServlet extends HttpServlet {

    @Autowired
    private OSSProperties ossProperties;

    @RequestMapping("ossFileUpload")
    public JsonUtil ossFileUpload(HttpServletRequest req, @RequestParam("file") MultipartFile file) throws ServletException, IOException {
        JsonUtil jsonUtil = null;
        try {
            jsonUtil = UploadFileUtil.uploadFileToOss(
                    ossProperties.getEndPoint(),
                    ossProperties.getAccessKeyId(),
                    ossProperties.getAccessKeySecret(),
                    file.getInputStream(),
                    ossProperties.getBucketName(),
                    ossProperties.getBucketDomain(),
                    file.getOriginalFilename());

        } catch (IOException e) {
            jsonUtil = new JsonUtil();
            e.printStackTrace();
            jsonUtil.setCode(1);
            jsonUtil.setMsg("文件上传失败:" + e.getMessage());
        }

        if (jsonUtil == null) {
            jsonUtil.setCode(0);
            jsonUtil.setMsg("文件上传失败");
        }

        return jsonUtil;
    }
}